﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Tracy.CoreLib.Data;
using Microsoft.Win32;
using Tracy.CoreLib;
using System.Runtime.InteropServices;
using System.Threading;
namespace Tracy.Agent.DownloaderAdapter
{
    public class ThunderAdapter : AbstractDownloaderAdapter, IDownloaderAdapter
    {
        public event EventHandler<EventArgsWithData> OnException;
        public override string HostProcessName
        {
            get
            {
                return Constants.CONST_APPLICATION_PROCESS_THUNDER;
            }
        }

        private string hostPath = null;
        public override string HostPath
        {
            get
            {
                if (hostPath == null)
                {
                    RegistryKey regdir = Registry.LocalMachine.OpenSubKey("SOFTWARE", false);
                    regdir = regdir.OpenSubKey("Thunder Network", false);
                    regdir = regdir.OpenSubKey("ThunderOem", false);
                    regdir = regdir.OpenSubKey("thunder_backwnd", false);
                    hostPath = regdir.GetValue("Path").ToString();
                }
                return hostPath;

            }
        }

        private Thread threadConfirmTask;
        private Thread threadAutoDialogHandler;
        private static EventWaitHandle whConfirmTask = new AutoResetEvent(false);
        private THUNDERAGENTLib.AgentClass agent;
        public ThunderAdapter()
        {
            agent = new THUNDERAGENTLib.AgentClass();
        }

        private void ConfirmTask(object input)
        {
            try
            {
                ResourceItem item = null;
                if (input is ResourceItem) item = (ResourceItem)input;
                else return;
                const int MAX_RETRY_TIMES_NEW_TASK_DIALOG_BT = 240; //120秒超时
                const int MAX_RETRY_TIMES_NEW_TASK_DIALOG_EM = 20; //10秒超时

                int timeout = 0;

                //查找添加任务对话框
                string thunderDialogTitle = "";
                if (item.Type == Constants.CONST_VALUE_TYPE_BT)
                {
                    thunderDialogTitle = "新建BT任务";
                    timeout = MAX_RETRY_TIMES_NEW_TASK_DIALOG_BT;
                }
                else
                {
                    thunderDialogTitle = "建立新的下载任务";
                    timeout = MAX_RETRY_TIMES_NEW_TASK_DIALOG_EM;
                }

                int dialoghWnd = 0;
                int retry = 0;

                do
                {
                    System.Threading.Thread.Sleep(500);
                    dialoghWnd = FindWindow("#32770", thunderDialogTitle);
                    retry++;
                    if (retry >= timeout) throw new Exception("找不到“" + thunderDialogTitle + "”对话框"); //超时退出 
                } while (dialoghWnd == 0 && !killThreadFlag);
                

                //发送回车
                PostMessage(dialoghWnd, WM_KEYDOWN, 13, 0);

                
                threadAutoDialogHandler = new Thread(new ThreadStart(AutoDialogHandler));
                threadAutoDialogHandler.Start();
                
            }
            catch (Exception e)
            {
                OnException(this, new EventArgsWithData(e));
            }
            finally
            {
                whConfirmTask.Set();
            }

        }

        private void AutoDialogHandler()
        {
            //int dialoghWnd = 0;
            //int retry = 0;
            //const int MAX_RETRY_TIMES_DIALOG = 10;  //1秒超时
            ////处理重复任务对话框
            //bool phaseA = false;
            //do
            //{
            //    System.Threading.Thread.Sleep(100);
            //    if (!phaseA) dialoghWnd = FindWindow("#32770", "重复任务提示");
            //    if (dialoghWnd != 0 || phaseA)
            //    {
            //        if (!phaseA) //发现重复任务窗口
            //        {
            //            phaseA = true;
            //            retry = 0;
            //            System.Threading.Thread.Sleep(100);
            //        }

            //        //发现重复任务直接重新下载-_-
            //        PostMessage(dialoghWnd, WM_KEYDOWN, 13, 0);

            //        //如果有“重新下载”窗口
            //        dialoghWnd = FindWindow("#32770", "重新下载");
            //        if (dialoghWnd != 0)
            //        {
            //            retry = 0;
            //            System.Threading.Thread.Sleep(100);
            //            //流氓到底，直接删掉以前的文件，重新下载
            //            PostMessage(dialoghWnd, WM_KEYDOWN, 13, 0);
            //        }
            //    }
            //    retry++;
            //} while (retry <= MAX_RETRY_TIMES_DIALOG);

            int dialoghWnd = 0;
            int retry = 0;
            const int MAX_RETRY_TIMES = 300;  //3秒超时
            //处理重复任务对话框
            do
            {
                System.Threading.Thread.Sleep(10);
                dialoghWnd = FindWindow("#32770", "重复任务提示");
                if (dialoghWnd != 0)
                {
                    System.Threading.Thread.Sleep(100);

                    //发现重复任务则不添加
                    PostMessage(dialoghWnd, WM_KEYDOWN, 27, 0);
                    retry = 0;
                }
                retry++;
            } while (retry <= MAX_RETRY_TIMES && !killThreadFlag);
        }


        public bool AddToDownload(ResourceItem item)
        {
            //向迅雷添加任务
            agent.AddTask(item.Link, null, item.Folder, null, null, 1, 0, 5);
            if (threadConfirmTask == null || threadConfirmTask.ThreadState == System.Threading.ThreadState.Stopped)
            {
                threadConfirmTask = new Thread(new ParameterizedThreadStart(ConfirmTask));
                threadConfirmTask.Start(item);
            }
            else
            {
                throw new TracyException(TracyException.EXCEPTION_THREAD_STILL_RUNNING);
            }
            agent.CommitTasks();
            whConfirmTask.WaitOne();

            return true;
        }
    }
}
